<?php
namespace app\user\model;

use app\common\model\TimeModel;
use org\Http;
use think\facade\Cache;

class User extends TimeModel
{

    static function onAfterUpdate(){
        $uid=session('userid');
        if($uid) {
            Cache::delete('user_'.$uid);
        }
    }

    public function attribute()
    {
        return $this->hasOne('UserAttribute', 'user_id', 'id');
    }

    static function getRandNames($limit)
    {
        $url = 'https://api.laysns.com/get_randomNames?UpdateKey=' . env('key'). '&limit=' . $limit;

        if ($line = Http::post($url)) {
            return json_decode($line, true);
        }
    }

    static function createUsername(){
        $username = 'user_'.create_random_str(8);
        $res = static::where(['username'=>$username])->find();
        if ($res) {
            static::createUsername();
        }else{
            return $username;
        }
    }

    public static function checkRegisterAuth(){
        $config = sysconfig('user');
        $model=new static();
        $ip=request()->ip();
        $todatTime=strtotime(date("Y-m-d"));
        if ($config['register_interval']) {
            $interval=$config['register_interval'];
            $lastSend = $model
                ->where('create_time','>',$todatTime)
                ->where('register_ip',$ip)
                ->order('id', 'desc')
                ->limit(1)
                ->value('create_time');
            if($lastSend&&($lastSend + 60 * $interval)>time()) {
                return array('code' => -1, 'msg' => '发送频率过快，请稍后再试');
            }
        }

        if ($config['ip_register_max']) {
            $ipMax = $config['ip_register_max'];
            $ipCount = $model
                ->where('create_time','>',$todatTime)
                ->where('ip',$ip)
                ->count();
            if ($ipCount >= $ipMax) {
                return array('code' => -1, 'msg' => '注册这么多账号作甚');
            }
        }
        return true;
    }


    public static function createNew($data){
        if(!isset($data['nickname'])){
            $nickNameArr=[
                '绛紫','跌堕','信仰','靛蓝','容颜','过往','温媪','青衣','轻念','酷刑','墨绿','悲漠','明暗','弱水',
                '风声','糜媚','黎开','瑟索','余空','麻里','色白','旧颜','花冢','蓑衣','吞花','灰烬','邪魅','暗色',
                '安梓','晓梦','简慕','撕裂','负荷','囙魂','绵绵','堇色','怨念','反讽','记得','淹没','时光','沧澜',
                '艳遇','茶蘼','刺槐','战徒','血腥','苦口','玩味','仓珥','矢车','蔷薇','吞噬','当绿','青奴','葵生',
                '未央','破棋','堇色','固执','剜心','花葭','束缚','留井',
                '莫小蛋','钱哆哆','布小心','苏子宣','皇甫笑','何呆呆','晴甜甜','猫小喵','卓晨雅','修静轩','萧子鸿',
                '美兮兮','许芊芊','洛倾颜','凉景懿','言灿璨','幕筱晨','迟冷熙','奈小落','田菜菜','北凌萱','淡蓝色',
                '诛笑靥','纷泪雨','花雨黯','黠心明','灰烟飞','爱还逝','樱花咒','溯汐潮','岚风殇','浅笑痕','笄发醒',
                '红颜殆','天若尘','泪染渍','发拂霜','泣幽鬼','追梦魂','瑶冰魄','萤飞觅','思寸灰','苦恋伊','莞尔笑',
                '笠蓑湿','清影觅','光彩影','花争发','泣梳妆','汝勿离','镜花月','参苓荃','凄寒注','若迈风','苦追忆',
                '愿遗忘','琴未醒','道独醉','幻流淌','血泪干','风独寒','瞳裂泣','爱茛笑','尧侪枫','芡苋青','花蕊衣',
                '裳棠栗','爱恨泯','洁莲璨','樱花祭','笠蓑湿','说爱我','红莲绽','双星聚','命之轮','史珍香',
                '史何毕','周宝霸','马辟京','胡理晶','煮天史','王九蛋',
                '繁华似锦','赢了爱情','痛定思痛','似水柔情','月光倾城','流绪微梦','残花败柳',
                '夏花依旧','演绎轮回','一抹红尘','悲欢自饮','稚气未脱','离经叛道','两重心事','心安勿忘','悲欢离合',
                '无处安放','残缺韵律','眼神调情','安然放心','内心深处','负面情绪','心有所属','时间在流','流年开花',
                '守住时间','静待死亡','梦绕魂牵','半世晨晓','惜你若命','单独隔离','寂寞盘旋','放心不下','往事随风',
                '年少无知','内心世界','沧桑笑容','微光倾城','乱试佳人','散场电影','折现浪漫','梦回旧景','今非昔比',
                '淡忘如思','眼角笑意','痴心绝对',
                '待到情浓时','两条麻花辫','还年幼的我','最后一抹红','自顾自美丽','比你强的多','陪我看日出','吹胡子瞪眼',
                '很喜欢红唇','抛空了理智','像某种频率','不论过多久','默契刚刚好','又何必改变','夜晚星空下','挥霍的青春',
                '季安末若素','暧昧总成伤·','华丽的情节','沦落成风尘','梅花浅妆离','一枝素上笔','蝉花惹人怜','黛服宫闱现'
            ];
            $data['nickname']=$nickNameArr[array_rand($nickNameArr)];
        }
        if(!isset($data['username'])){
            $data['username']=static::createUsername();
        }
        $saveData=[
            'uuid'=>md5(uniqid() . microtime()),
            'salt'=>create_random_str(16),
            'register_ip'=>request()->ip(),
        ];

        if(!isset($data['avatar'])||!$data['avatar']){
            $imgId=rand(0,19);
            $data['avatar']='/static/common/images/avatars/'.$imgId.'.jpg';
        }
        $addParent=self::addParentId($data);
        if(count($addParent)){
            $data=array_merge($data,$addParent);
        }

        if(isset($data['password'])) {
            $saveData['password'] = md5($data['password'] . $saveData['salt']);
        }
        $user=(new static())->create(array_merge($data,$saveData));
        UserAttribute::create(['user_id'=>$user->id]);
        return $user;
    }

    public static function addParentId($data){
        //上上级
        $promo_code='';
        if(isset($data['promo_code'])) {
            $promo_code=remove_xss($data['promo_code']);
        }else if(cookie('pid')) {
            $promo_code = cookie('pid');
        }
        $return=[];
        if($promo_code){
            $referrerUser = static::where('promo_code',$promo_code)->find();
            if ($referrerUser) {
                $return['referrer_id'] = $referrerUser->id;
                $return['referrer2_id'] = $referrerUser->referrer_id;
                $return['referrer3_id'] = $referrerUser->referrer2_id;
            }
        }

        return $return;
    }

}